﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;

namespace XP_More
{
	class Settings
	{
		Dictionary<string, string> m_settings = new Dictionary<string, string>();
		// store settings in an alternate data stream of the executable, to keep portable
		// might not work on some directories, but settings aren't critical anyway -
		// worst comes to worst, user will have to locate the VM folder again or so.
		const string m_settingsStream = "settings";

		public void Load()
		{
			byte[] settings = AlternateDataStreams.ADSFile.Read(Application.ExecutablePath, "settings");
			if (settings == null)	// no settings
				return;
			try
			{
				MemoryStream memStream = new MemoryStream();
				memStream.Write(settings, 0, settings.Length);
				memStream.Position = 0;

				BinaryFormatter binFormatter = new BinaryFormatter();
				m_settings = (Dictionary<string, string>)binFormatter.Deserialize(memStream);
				memStream.Close();
			}
			catch (Exception ex)
			{
				// basically swallow the exception. not having settings is not a critical problem.
				Console.Out.WriteLine("Error reading from settings file {0}:{1} -\n{2}", 
					Application.ExecutablePath, m_settingsStream, ex.ToString());
			}
		}

		public void Save()
		{
			try
			{
				MemoryStream memStream = new MemoryStream();
				BinaryFormatter binFormatter = new BinaryFormatter();
				binFormatter.Serialize(memStream, m_settings);
				byte[] settings = memStream.GetBuffer();
				AlternateDataStreams.ADSFile.Write(settings, Application.ExecutablePath, "settings");
				memStream.Close();
			}
			catch (Exception ex)
			{
				// basically swallow the exception. not having settings is not a critical problem.
				Console.Out.WriteLine("Error writing to settings file {0}:{1} -\n{2}",
					Application.ExecutablePath, m_settingsStream, ex.ToString());
			}
		}

		public string Get(string setting)
		{
			string value = "";
			if (m_settings.TryGetValue(setting, out value))
				return value;
			return "";
		}

		public void Set(string setting, string val)
		{
			m_settings[setting] = val;
		}
	}
}
